var express = require("express");
var router = express.Router();
// var async = require("async");
const comment = require("../model/comment");
const comfabulous = require("../model/comfabulous");
const answer = require("../model/answer");
const like = require("../model/like");
router.post("/api/v1/getAnswers", async (req, res) => {
  console.log(req.body);
  let answerData = answer.find(req.body.query).populate({path: 'userid',populate:{path:'department'}});

  if (req.body.sort) {
    answerData.sort(req.body.sort);
  }

  if (req.body.skip) {
    answerData.skip(req.body.skip);
  }
  if (req.body.limit) {
    answerData.limit(req.body.limit);
  }
  let result = await answerData.exec();
  for (let index = 0; index < result.length; index++) {
    const element = result[index];
    let fistComment = await comment
      .find({
        articleid: element._id,
      })
      .populate("userid");

    for (let index2 = 0; index2 < fistComment.length; index2++) {
      let element2 = fistComment[index2];
      let secondComment = await comfabulous
        .find({
          commentid: element2._id,
        })
        .populate(["userid", "replyid"]);
      element2._doc.secondComment = secondComment;
    }
    let likeData = await like.find({
      answer_id: element._id,
      userid: req.body.likeUserId,
    });
    let Like = {
      isLike: false
    };
    if (likeData.length != 0) {
      Like.isLike = true;
      Like._id = likeData[0]._id
    }
    result[index]._doc.Like = Like;
    result[index]._doc.fistCom = fistComment;
    result[index]._doc.showCom = 3;
  }
  let countnum;
  if (req.body.count) {
    countnum = await answer.find({
      problem_id: req.body.query.problem_id
    }).count();
  }
  res.json({
    code: 200,
    data: result,
    countnum: countnum,
  });

  // let articleid = req.body.query.articleid;
  // let fistComment = comment.find({
  //   articleid: articleid
  // }).populate("userid");

  // if (req.body.skip) {
  //   fistComment.skip(req.body.skip)
  // }
  // if (req.body.limit) {
  //   fistComment.limit(req.body.limit)
  // }
  // let result = await fistComment.exec();

  // for (let index = 0; index < result.length; index++) {
  //   let element = result[index];
  //   let secondComment = await comfabulous
  //     .find({
  //       commentid: element._id
  //     })
  //     .populate(["userid", "replyid"]);
  //   element._doc.secondComment = secondComment;
  // }
  // let countnum
  // if (req.body.count) {
  //   countnum = await comment.find({
  //     articleid: articleid
  //   }).count();
  // }
  // res.json({
  //   code: 200,
  //   data: result,
  //   countnum: countnum
  // });
});

// 导出模块（在 app.js 中引入）
module.exports = router;